//
//  TransactionHeadView.m
//  Exchange
//
//  Created by 张庆勇 on 2018/7/13.
//  Copyright © 2018年 张庆勇. All rights reserved.
//
#import "TransactionHeadView.h"
#import "JGPopView.h"
#import "TransactionCell.h"
#import "LoginViewController.h"
#import "IdentityAuthenticationViewController.h"
#import "FailViewController.h"
#import "CheckVersionAlearView.h"
#import "UIImage+Gradient.h"
@interface TransactionHeadView ()<selectIndexPathDelegate,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property (nonatomic,strong)NSArray * asks;
@property (nonatomic,strong)NSArray * bids;
@property (nonatomic,assign)BOOL canEditing;
@property (nonatomic,strong)NSString * page;
@property (nonatomic,strong)NSString * numpage;
@end
@implementation TransactionHeadView
#pragma JGPopViewDelegate
- (void)selectIndexPathRow:(NSInteger)index{
    _canEditing = (index == 0)? YES:NO; //限价 //市价
    [self variableWithUI];
    [_chooseType setTitleEdgeInsets:UIEdgeInsetsMake(0, -_chooseType.imageView.width , 0, _chooseType.imageView.width)];
    [_chooseType setImageEdgeInsets:UIEdgeInsetsMake(0, _chooseType.titleLabel.width + 10, 0, - _chooseType.titleLabel.width)];
}
- (void)variableWithUI
{
    NSArray *namearray = [self.modle.name componentsSeparatedByString:@"_"];
    if (_canEditing) {
        
        [_chooseType setTitle:Localized(@"transaction_Limited_transaction") forState:(UIControlStateNormal)];
        _priceField.placeholder = Localized(@"hone_price");
        _priceValue.hidden = NO;
        [_addbutton setTitle:@"+" forState:0];
        [_reduceButton setTitle:@"-" forState:0];
        _priceField.text = [EXUnit formatternumber:_modle.quote_asset_precision.intValue assess:_modle.last];
        _page = _priceField.text;
        _priceValue.text = [EXUnit getBTBPriceWithName:namearray[1] Price:_priceField.text];
        _numField.placeholder =  Localized(@"hone_num");
        
    }else
    {
        _priceField.placeholder = Localized(@"transaction_market_message");
        _priceField.text = @"";
        
        [_chooseType setTitle:Localized(@"transaction_Market_transaction") forState:(UIControlStateNormal)];
        _priceValue.hidden = YES;
        [_addbutton setTitle:@"" forState:0];
        [_reduceButton setTitle:@"" forState:0];
        _numField.placeholder = _isSell?  Localized(@"hone_num"):Localized(@"transaction_turnover");
        [self RefreshThePrice];
    }
    [self tradingBalance];
}
// 购买
- (void)buy:(UIButton *)button
{
    if (![EXUserManager isLogin])
    {
        [self SetThePassword];
        return;
    }
    if ([AppDelegate shareAppdelegate].is_preaudit.integerValue ==1) //如果等于0没有认证也可以购买
    {
        if ([EXUserManager RealName].integerValue ==0) { //未认证
            CheckVersionAlearView * aleartVC = [[CheckVersionAlearView alloc] initWithmessage:Localized(@"transaction_authenticated_message")
                                                                                     titleStr:Localized(@"transaction_authenticated_title")
                                                                                      openUrl:@""
                                                                                      confirm:Localized(@"transaction_OK")
                                                                                       cancel:Localized(@"transaction_cancel")
                                                                                        state:2
                                                                                RechargeBlock:^
                                                {
                                                    
                                                    IdentityAuthenticationViewController * idACationVC = [[IdentityAuthenticationViewController alloc] init];
                                                    idACationVC.title = Localized(@"my_identity_authentication");
                                                    [[EXUnit currentViewController].navigationController pushViewController:idACationVC animated:YES];
                                                    
                                                    
                                                }];
            aleartVC.animationStyle = LXASAnimationTopShake;
            [aleartVC showLXAlertView];
            return;
        }else if ([EXUserManager RealName].integerValue ==1||[EXUserManager RealName].integerValue ==4)//审核中
        {
            [EXUnit showMessage:Localized(@"C2C_under_review")];
            return;
            
        }else if ([EXUserManager RealName].integerValue ==3)//认证失败
        {
            CheckVersionAlearView * aleartVC = [[CheckVersionAlearView alloc] initWithmessage:Localized(@"transaction_authenticated_failed")
                                                                                     titleStr:Localized(@"transaction_authenticated_title")
                                                                                      openUrl:@""
                                                                                      confirm:Localized(@"transaction_OK")
                                                                                       cancel:Localized(@"transaction_cancel")
                                                                                        state:2
                                                                                RechargeBlock:^
                                                {
                                                    
                                                    IdentityAuthenticationViewController * idACationVC = [[IdentityAuthenticationViewController alloc] init];
                                                    idACationVC.title = Localized(@"my_identity_authentication");
                                                    [[EXUnit currentViewController].navigationController pushViewController:idACationVC animated:YES];
                                                    
                                                    
                                                }];
            aleartVC.animationStyle = LXASAnimationTopShake;
            [aleartVC showLXAlertView];
            
            return;
            
        }
    }
    
    if (_numField.text.length ==0 ||_numField.text.doubleValue <0)
    {
        [EXUnit showMessage:Localized(@"transaction_quantity")];
        return;
    }
    if (_canEditing) {
        if (_priceField.text.floatValue<_modle.min_quantity.floatValue) {
            [EXUnit showMessage:[NSString stringWithFormat:@"%@%@",_isSell?Localized(@"transaction_price_sell"):Localized(@"transaction_pricet_buy"),_modle.min_quantity]];
            return;
        }
    }
    if (_numField.text.floatValue<_modle.min_quantity.floatValue) {
        [EXUnit showMessage:[NSString stringWithFormat:@"%@%@",_isSell?Localized(@"transaction_least_sell"):Localized(@"transaction_least_buy"),_modle.min_quantity]];
        return;
    }
    
    WeakSelf
    if ([AppDelegate shareAppdelegate].isBecomeActive) {
        if ([EXUnit isOpenTouchid] && ![EXUnit isOpenGesture]) {
            [YWFingerprintVerification fingerprintVerificationCallBack:^(NSError *error) {
                if(!error){
                    //验证成功，主线程处理UI
                    dispatch_async(dispatch_get_global_queue(0, 0), ^{
                        // 处理耗时操作的代码块...
                        
                        //通知主线程刷新
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [weakSelf Buy:button];
                        });
                        
                    });
                }else{
                    //验证成功，主线程处理UI
                    dispatch_async(dispatch_get_global_queue(0, 0), ^{
                        // 处理耗时操作的代码块...
                        
                        //通知主线程刷新
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [EXUserManager removeUserInfo];
                            [weakSelf SetThePassword];
                        });
                        
                    });
                    
                }
            }];
        }else if (![EXUnit isOpenTouchid] && [EXUnit isOpenGesture])
        {
            //验证手势密码
            [YWUnlockView showUnlockViewWithType:YWUnlockViewUnlock callBack:^(BOOL result) {
                if (result) {
                    [weakSelf Buy:button];
                }else
                {
                    [EXUserManager removeUserInfo];
                    [weakSelf SetThePassword];
                }
            }];
            
        }else if (![EXUnit isOpenTouchid] && ![EXUnit isOpenGesture])
        {
            [weakSelf Buy:button];
        }
    }else
    {
        [weakSelf Buy:button];
    }
}
- (void)Buy:(UIButton *)button
{
    [AppDelegate shareAppdelegate].isBecomeActive = NO;
    NSDictionary * dataDic;
    NSString * httpApi;
    if (_canEditing) { //限价交易
        dataDic = @{@"market":_modle.name,
                    @"side": _isSell? @"1":@"2",
                    @"amount":_numField.text,
                    @"price":_priceField.text
                    };
        httpApi = tradelimit;
    }else //市价
    {
        dataDic = @{@"market":_modle.name,
                    @"side":_isSell? @"1":@"2",
                    @"amount":_numField.text,
                    };
        httpApi = trademarket;
    }
    button.userInteractionEnabled = NO;
    
    [HomeViewModel getTradeWithDic:dataDic url:httpApi callBack:^(BOOL isSuccess, id callBack) {
        
        button.userInteractionEnabled = YES;
        if (isSuccess) {
            [self initTextField];
            if (self.buySuccess) {
                self.buySuccess(YES);
            }
        }
    }];
    
}
- (void)initTextField
{
    _numField.text = @"";
    [self getslider:0];
    
}
- (void)SetThePassword
{
    LoginViewController * loginView = [[LoginViewController alloc] init];
    [[EXUnit currentViewController] presentViewController:loginView animated:YES completion:nil];
}
- (void)valueChangeAction:(CCHStepSizeSlider *)sender {
    
    if (_balance.length ==0 ||_balance.doubleValue <0) {
        [self getslider:0];
        return;
    }
    if (!_isSell &&_canEditing) {
        
        switch (sender.index) {
            case 0:
                _numField.text = @"";
                _numpage = _numField.text;
                [self RefreshThePrice];
                [self tradingBalance];
                
                break;
            case 1:
            {
                NSString * price  = [NSString stringWithFormat:@"%@",@(_balance.doubleValue/_priceText.doubleValue *0.25)];
                _numField.text = [EXUnit formatternumber:_modle.base_asset_precision.intValue assess:price];
                _numpage = _numField.text;
                
                [self RefreshThePrice];
            }
                
                break;
            case 2:
            {
                NSString * price  = [NSString stringWithFormat:@"%@",@(_balance.doubleValue/_priceText.doubleValue*0.5)];
                _numField.text = [EXUnit formatternumber:_modle.base_asset_precision.intValue assess:price];
                _numpage = _numField.text;
                [self RefreshThePrice];
            }
                
                break;
            case 3:
            {
                NSString * price = [NSString stringWithFormat:@"%@",@(_balance.doubleValue/_priceText.doubleValue*0.75)];
                _numField.text = [EXUnit formatternumber:_modle.base_asset_precision.intValue assess:price];
                _numpage = _numField.text;
                [self RefreshThePrice];
            }
                
                break;
            case 4:
            {
                NSString * price = self.buybalance;
                _numField.text = [EXUnit formatternumber:_modle.base_asset_precision.intValue assess:price];
                _numpage = _numField.text;
                [self RefreshThePrice];
            }
                
                break;
            default:
                break;
        }
        
    }else
    {
        switch (sender.index) {
            case 0:
                _numField.text = @"";
                _numpage = _numField.text;
                [self RefreshThePrice];
                
                break;
            case 1:
            {
                NSString * price  = [NSString stringWithFormat:@"%@",@(_balance.doubleValue*0.25)];
                _numField.text = [EXUnit formatternumber:_modle.base_asset_precision.intValue assess:price];
                _numpage = _numField.text;
                
                [self RefreshThePrice];
            }
                
                break;
            case 2:
            {
                NSString * price  = [NSString stringWithFormat:@"%@",@(_balance.doubleValue*0.5)];
                _numField.text = [EXUnit formatternumber:_modle.base_asset_precision.intValue assess:price];
                _numpage = _numField.text;
                [self RefreshThePrice];
            }
                
                break;
            case 3:
            {
                NSString * price = [NSString stringWithFormat:@"%@",@(_balance.doubleValue*0.75)];
                _numField.text = [EXUnit formatternumber:_modle.base_asset_precision.intValue assess:price];
                _numpage = _numField.text;
                [self RefreshThePrice];
            }
                
                break;
            case 4:
            {
                NSString * price = [NSString stringWithFormat:@"%@",@(_balance.doubleValue*1)];
                _numField.text = [EXUnit formatternumber:_modle.base_asset_precision.intValue assess:price];
                _numpage = _numField.text;
                [self RefreshThePrice];
            }
                
                break;
            default:
                break;
        }
        
        
    }
    
}

- (void)RefreshThePrice
{
    
    
    if (_canEditing) {
        _page = _priceField.text;
        _priceText = [NSString stringWithFormat:@"%@",_page];
    }
    
    _numpage = _numField.text;
    NSArray *namearray = [self.modle.name componentsSeparatedByString:@"_"];
    _priceValue.text = [EXUnit getBTBPriceWithName:namearray[1] Price:_priceField.text];
    
    if ([EXUserManager isLogin] || ![NSString isEmptyString:[EXUserManager userInfo].token]) {
        
        if (_isSell)
        {
            if (_numField.text.doubleValue/_balance.doubleValue *100 <10) {
                
                [self getslider:0];
                
            }else if (_numField.text.doubleValue/_balance.doubleValue *100 >10 && _numField.text.doubleValue/_balance.doubleValue *100 <26)
            {
                [self getslider:1];
            }else if (_numField.text.doubleValue/_balance.doubleValue *100 >25 && _numField.text.doubleValue/_balance.doubleValue *100 <30)
            {
                [self getslider:1];
            }else if (_numField.text.doubleValue/_balance.doubleValue *100 >30 && _numField.text.doubleValue/_balance.doubleValue *100 <51)
            {
                [self getslider:2];
            }else if (_numField.text.doubleValue/_balance.doubleValue *100 >50 && _numField.text.doubleValue/_balance.doubleValue *100 <60)
            {
                [self getslider:2];
            }else if (_numField.text.doubleValue/_balance.doubleValue *100 >60 && _numField.text.doubleValue/_balance.doubleValue *100 <76)
            {
                [self getslider:3];
            }else if (_numField.text.doubleValue/_balance.doubleValue *100 >75 && _numField.text.doubleValue/_balance.doubleValue *100 <85)
            {
                [self getslider:3];
            }else if ((_numField.text.doubleValue/_balance.doubleValue *100 >85 && _numField.text.doubleValue/_balance.doubleValue *100 <100) ||_numField.text.doubleValue/_balance.doubleValue *100==100)
            {
                [self getslider:4];
                
            }else if (_numField.text.doubleValue/_balance.doubleValue *100 >=100)
            {
                [self getslider:4];
                _numField.text = [EXUnit formatternumber:_modle.base_asset_precision.intValue assess:_balance];
                
                
                //                 [EXUnit showMessage:Localized(@"transaction_Exceed_balance")];
            }
        }else
        {
            double toall = _numField.text.doubleValue * _priceText.doubleValue;
            if (toall==0)
            {
                [self getslider:0];
                return;
            }
            if (toall/_balance.doubleValue *100 <10) {
                
                [self getslider:0];
                
            }else if (toall/_balance.doubleValue *100 >10 && toall/_balance.doubleValue *100 <26)
            {
                [self getslider:1];
            }else if (toall/_balance.doubleValue *100 >25 && toall/_balance.doubleValue *100 <30)
            {
                [self getslider:1];
            }else if (toall/_balance.doubleValue *100 >30 && toall/_balance.doubleValue *100 <51)
            {
                [self getslider:2];
            }else if (toall/_balance.doubleValue *100 >50 && toall/_balance.doubleValue *100 <60)
            {
                [self getslider:2];
            }else if (toall/_balance.doubleValue *100 >60 && toall/_balance.doubleValue *100 <76)
            {
                [self getslider:3];
            }else if (toall/_balance.doubleValue *100 >75)
            {
                [self getslider:4];
            }else if ((toall/_balance.doubleValue *100 >75 && toall/_balance.doubleValue *100 <100) ||toall/_balance.doubleValue *100==100)
            {
                [self getslider:4];
                
            }else if (toall/_balance.doubleValue *100 >100)
            {
                [self getslider:4];
                
            }
        }
    }
    [self tradingBalance];
    
    
    //    NSString * total = [NSString stringWithFormat:@"%f",_priceField.text.doubleValue*_numField.text.doubleValue];
    NSString * total = [EXUnit formatternumber:_modle.quote_asset_precision.intValue assess:[NSString stringWithFormat:@"%f",_priceField.text.doubleValue*_numField.text.doubleValue]];
    
    _ATurnover.attributedText = [EXUnit finderattributedString:[NSString stringWithFormat:@"%@ %@ %@",Localized(@"C2C_Total"),total,namearray[1]]
                                              attributedString:[NSString stringWithFormat:@"%@",namearray[1]]
                                                         color:MAINTITLECOLOR
                                                          font:AutoFont(12)];
    if (self.priceBlock) {
        self.priceBlock(_priceField.text);
    }
    
}
-(void)textFieldDidChange :(UITextField *)TextField{
    if (TextField ==_priceField) {
        
        _page =  _priceField.text;
    }else if (TextField ==_numField)
    {
        _numpage = _numField.text;
        [self tradingBalance];
    }
    
    [self RefreshThePrice];
}
//减去
- (void)reduce:(UIButton *)button
{
    
    if (button.tag ==0) { //修改价格
        if (!_canEditing) {
            return;
        }
        if (_priceField.text.doubleValue <0 ||_priceField.text.doubleValue==0)
        {
            return;
        }
        NSDecimalNumber*jian1 = [NSDecimalNumber decimalNumberWithString:_page];
        NSDecimalNumber*jian2 = [NSDecimalNumber decimalNumberWithString:_modle.tick_size];
        NSDecimalNumber*jian = [jian1 decimalNumberBySubtracting:jian2];
        _page = [NSString stringWithFormat:@"%@",jian] ;
        if (_page<0) {
            _priceField.text =[EXUnit formatternumber:_modle.quote_asset_precision.intValue assess:@"0"];
            
        }else
        {
            _priceField.text = [EXUnit formatternumber:_modle.quote_asset_precision.intValue assess:[NSString stringWithFormat:@"%@",_page]];
        }
        
        
    }else //修改数量
    {
        if (_numField.text.doubleValue<0 || _numField.text.doubleValue==0) {
            return;
        }
        
        NSDecimalNumber*jian1 = [NSDecimalNumber decimalNumberWithString:_numpage];
        NSDecimalNumber*jian2 = [NSDecimalNumber decimalNumberWithString:_modle.min_quantity];
        NSDecimalNumber*jian = [jian1 decimalNumberBySubtracting:jian2];
        _numpage = [NSString stringWithFormat:@"%@",jian] ;
        if (_numpage<0) {
            _numField.text =[EXUnit formatternumber:_modle.base_asset_precision.intValue assess:@"0"];
        }else
        {
            _numField.text = [EXUnit formatternumber:_modle.base_asset_precision.intValue assess:[NSString stringWithFormat:@"%@",_numpage]];
        }
        
    }
    
    [self RefreshThePrice];
    
}
//加
- (void)add:(UIButton *)button
{
    if (button.tag ==0) { //修改价格
        if (!_canEditing) {
            return;
        }
        if ([NSString isEmptyString:_page])
        {
            _page = [EXUnit formatternumber:_modle.quote_asset_precision.intValue assess:@"0"];
        }
        NSDecimalNumber*jia1 = [NSDecimalNumber decimalNumberWithString:_page];
        NSDecimalNumber*jia2 = [NSDecimalNumber decimalNumberWithString:_modle.tick_size];
        //减法运算函数  decimalNumberByAdding
        NSDecimalNumber*jia = [jia1 decimalNumberByAdding:jia2];
        _page = [NSString stringWithFormat:@"%@",jia] ;
        _priceField.text = [EXUnit formatternumber:_modle.quote_asset_precision.intValue assess:[NSString stringWithFormat:@"%@",_page]];
    }else //修改数量
    {
        if ([NSString isEmptyString:_numpage])
        {
            _numpage = [EXUnit formatternumber:_modle.base_asset_precision.intValue assess:@"0"];
        }
        NSDecimalNumber*jia1 = [NSDecimalNumber decimalNumberWithString:_numpage];
        NSDecimalNumber*jia2 = [NSDecimalNumber decimalNumberWithString:_modle.min_quantity];
        //减法运算函数  decimalNumberByAdding
        NSDecimalNumber*jia = [jia1 decimalNumberByAdding:jia2];
        _numpage = [NSString stringWithFormat:@"%@",jia] ;
        _numField.text = [EXUnit formatternumber:_modle.base_asset_precision.intValue assess:[NSString stringWithFormat:@"%@",_numpage]];
    }
    [self RefreshThePrice];
}
- (NSDecimalNumber *)decimalNumber:(double)num {
    NSString *numString = [NSString stringWithFormat:@"%lf", num];
    return [NSDecimalNumber decimalNumberWithString:numString];
}
- (void)transactionButton:(UIButton *)button
{
    NSArray * dataArray = @[Localized(@"transaction_Limited_transaction"),Localized(@"transaction_Market_transaction")];
    CGPoint point = CGPointMake( 15 + button.titleLabel.mj_x + button.titleLabel.width + 18 + button.imageView.width/2,button.bottom+5);
    CGFloat with = RealValue_W(160);
    JGPopView *view2 = [[JGPopView alloc] initWithOrigin:point Width:with Height:dataArray.count * RealValue_W(80) Type:JGTypeOfUpRight Color:TRABSACTIONColor];
    view2.dataArray = dataArray;
    view2.row_height = 40;
    view2.delegate = self;
    [view2 popView];
    [self addSubview:view2];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = TABLEVIEWLCOLOR;
        [self get_up];
        
    }
    return self;
    
}
- (void)refushUIdataWithModle:(HomeModle *)modle;
{
    _modle = modle;
    NSArray *namearray = [self.modle.name componentsSeparatedByString:@"_"];
    _numField.text = @"";
    _priceValue.text = [EXUnit getBTBPriceWithName:namearray[1] Price:_modle.last];
    NSString * range;
    float _x = modle.IncreaseDegree.floatValue;
    if (!isnan(_x)) {
        if (modle.last.floatValue - modle.open.floatValue >=0) {
            range = [NSString stringWithFormat:@"+ %.2f%%",modle.IncreaseDegree.floatValue];
            self.priceLable.textColor = ZHANGCOLOR;
            self.rangeLable.textColor = ZHANGCOLOR;
        }else
        {
            range = [NSString stringWithFormat:@"%.2f%%",modle.IncreaseDegree.floatValue];
            self.priceLable.textColor =DIEECOLOR;
            self.rangeLable.textColor = DIEECOLOR;
        }
        
    }else
    {
        range = @"0.00%";
    }
    _priceText = [EXUnit formatternumber:_modle.quote_asset_precision.intValue assess:_modle.last];
    _priceLable.text = _priceText;
    _rangeLable.text = range;
    _numpage = _numField.text;
    _page = _priceField.text;
    [self initTextField];
    [self variableWithUI];
}
/*交易*/
- (void)tradingBalance
{
    if (!_canEditing)
    {
        _ATurnover.hidden = YES;
        _sellnumLabValue.hidden = YES;
        _numLabValue.hidden = NO;
    }else if (_canEditing)
    {
        if (_numField.text.length>0)
        {
            _sellnumLabValue.hidden = YES;
            _numLabValue.hidden = YES;
            _ATurnover.hidden = NO;
        }else
        {
            _sellnumLabValue.hidden = NO;
            _numLabValue.hidden = NO;
            _ATurnover.hidden = YES;
        }
    }
}
- (void)get_up
{
    NSArray * titles = @[Localized(@"C2C_buy1"),Localized(@"C2C_sell1")];
    for (int i=0; i<titles.count; i++) {
        UIButton * newButton = [[UIButton alloc] initWithFrame:CGRectMake(15 +i*86, RealValue_W(28),  RealValue_W(172) ,31)];
        [newButton setTitle:titles[i] forState:UIControlStateNormal];
        newButton.titleLabel.font = AutoBoldFont(14);
        [newButton setBackgroundColor:[ZBLocalized sharedInstance].textfieldBgColor forState:UIControlStateNormal];
        [newButton addTarget:self action:@selector(buttonbuyClick:) forControlEvents:(UIControlEventTouchUpInside)];
        newButton.tag = i;
        
        if (i == 0) {
            _purchaseButton = newButton;
            [newButton setTitleColor:ZHANGCOLOR forState:UIControlStateNormal];
            [newButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
            [newButton setBackgroundColor:ZHANGCOLOR forState:UIControlStateSelected];
            CAShapeLayer *maskLayer = [CAShapeLayer layer];
            maskLayer.path = [UIBezierPath bezierPathWithRoundedRect:newButton.bounds byRoundingCorners:UIRectCornerTopLeft  |UIRectCornerBottomLeft  cornerRadii:CGSizeMake(2, 2)].CGPath;
            newButton.layer.mask = maskLayer;
        }else
        {
            _sellButton = newButton;
            [newButton setTitleColor:DIEECOLOR forState:UIControlStateNormal];
            [newButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
            [newButton setBackgroundColor:DIEECOLOR forState:UIControlStateSelected];
            CAShapeLayer *maskLayer = [CAShapeLayer layer];
            maskLayer.path = [UIBezierPath bezierPathWithRoundedRect:newButton.bounds byRoundingCorners: UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:CGSizeMake(2, 2)].CGPath;
            newButton.layer.mask = maskLayer;
        }
        [self addSubview:newButton];
    }
    
    [self addSubview:self.chooseType];
    [self addSubview:self.pricetitle];
    [self addSubview:self.numbertitle];
    [self addSubview:self.ToptableView];
    [self addSubview:self.priceLable];
    [self addSubview:self.rangeLable];
    [self addSubview:self.bottombleView];
    
    [self initUI];
    [self getslider:0];
    [self addSubview:self.buyButton];
    _numLabValue.mj_y = self.buyButton.mj_y - RealValue_W(34) - RealValue_W(34) - RealValue_W(15) - RealValue_W(24);
    [self addSubview:self.sellnumLabValue];
    [self addSubview:self.ATurnover];
    
    
    NSArray * imgs = @[@"diebuttonIcon",@"hebuttonIcon",@"zhangbuttonIcon"];
    for (int i =0; i<imgs.count; i++) {
        UIButton * button  =[[UIButton alloc] initWithFrame:CGRectMake(_pricetitle.mj_x + RealValue_W(102)*i, self.buyButton.bottom - RealValue_W(32), RealValue_W(102), RealValue_W(32))];
        [button setImage:[UIImage imageNamed:imgs[i]] forState:0];
        [button setBackgroundColor:[ZBLocalized sharedInstance].textfieldBgColor  forState:UIControlStateNormal];
        [button setBackgroundColor:[ZBLocalized sharedInstance].selectedbuttonBgColor  forState:UIControlStateSelected];
        button.tag = i;
        
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
        if (button.tag ==1) {
            _chooseButton = button;
            _chooseButton.selected = YES;
            
        }
        
    }
    UIView * lineview = [[UIView alloc] initWithFrame:CGRectMake(0, self.height - 10, UIScreenWidth, 10)];
    lineview.backgroundColor = [ZBLocalized sharedInstance].BgViewLightColor;
    [self addSubview:lineview];
    
}
- (void)buttonClick:(UIButton *)button
{
    if (button !=_chooseButton) {
        button.selected = YES;
        _chooseButton.selected = NO;
        _chooseButton = button;
    }
    if (self.askAndbidBlock) {
        self.askAndbidBlock(button);
    }
    switch (button.tag) {
        case 0:
        {
            _ToptableView.hidden = NO;
            _bottombleView.hidden = YES;
            _ToptableView.mj_y = _pricetitle.bottom + RealValue_W(20);
            _ToptableView.height = RealValue_W(460);
            _priceLable.mj_y = _ToptableView.bottom;
            _rangeLable.mj_y = _priceLable.mj_y;
            
            
        }
            break;
        case 1:
        {
            
            _ToptableView.hidden = NO;
            _bottombleView.hidden = NO;
            _bottombleView.height = RealValue_W(210);
            _ToptableView.height = RealValue_W(210);
            
            _ToptableView.mj_y = _pricetitle.bottom + RealValue_W(20);
            _priceLable.mj_y = _ToptableView.bottom;
            _rangeLable.mj_y = _priceLable.mj_y;
            _bottombleView.mj_y = _priceLable.bottom;
            
            
            
        }
            break;
        case 2:
        {
            _ToptableView.hidden = YES;
            _bottombleView.hidden = NO;
            _bottombleView.mj_y = _pricetitle.bottom + RealValue_W(20);
            _bottombleView.height = RealValue_W(460);
            _priceLable.mj_y = _bottombleView.bottom;
            _rangeLable.mj_y = _priceLable.mj_y;
        }
            break;
            
        default:
            break;
    }
}
- (void)buttonbuyClick:(UIButton *)button
{
    [self initTextField];
    if (self.buttonBlock) {
        self.buttonBlock(button);
    }
}
- (void)initUI
{
    _canEditing = YES;
    NSArray * value = @[@"",@""];
    NSArray * placeholders = @[Localized(@"hone_price"),Localized(@"hone_num")];
    for (int i=0; i<2; i++)
    {
        UIButton * reduceButton = [UIButton dd_buttonCustomButtonWithFrame:CGRectMake(15, _chooseType.bottom +RealValue_W(24) +i*RealValue_W(134), RealValue_W(66), RealValue_W(66)) title:@"-" backgroundColor:[ZBLocalized sharedInstance].textfieldBgColor titleColor:MAINTITLECOLOR1 tapAction:^(UIButton *button) {
            [self reduce:button];
        }];
        reduceButton.tag=i;
        reduceButton.titleLabel.font =AutoFont(18);
        
        
        if (i ==0)
        {
            _reduceButton = reduceButton;
        }
        
        [self addSubview:reduceButton];
        
        UITextField * textField = [[UITextField alloc] initWithFrame:CGRectMake(reduceButton.right, reduceButton.mj_y, RealValue_W(214), reduceButton.height)];
        
        textField.textAlignment = NSTextAlignmentCenter;
        textField.placeholder = placeholders[i];
        textField.font = AutoBoldFont(15);
        textField.textColor = MAINTITLECOLOR;
        textField.delegate = self;
        textField.tintColor = TABTITLECOLOR;
        textField.backgroundColor = [ZBLocalized sharedInstance].textfieldBgColor;
        [textField setValue:textFieldPCOLOR forKeyPath:@"_placeholderLabel.textColor"];
        [textField setValue:AutoBoldFont(12)forKeyPath:@"_placeholderLabel.font"];
        textField.keyboardType = UIKeyboardTypeDecimalPad;
        [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        [self addSubview:textField];
        
        UIButton * addButton = [UIButton dd_buttonCustomButtonWithFrame:CGRectMake(textField.right, reduceButton.mj_y, reduceButton.width, reduceButton.height) title:@"+" backgroundColor:[ZBLocalized sharedInstance].textfieldBgColor  titleColor:MAINTITLECOLOR1 tapAction:^(UIButton *button) {
            [self add:button];
        }];
        addButton.titleLabel.font =AutoFont(18);
        addButton.tag=i;
        if (i==0) {
            _addbutton = addButton;
        }
        
        [self addSubview:addButton];
        
        UILabel * valuelable = [[UILabel alloc] initWithFrame:CGRectMake(reduceButton.mj_x, reduceButton.bottom +RealValue_W(17), RealValue_W(344), RealValue_W(34))];
        valuelable.text = value[i];
        valuelable.textColor = MAINTITLECOLOR1;
        valuelable.font = AutoFont(12);
        [self addSubview:valuelable];
        if (i==0) {
            _priceField = textField;
            
            _priceValue = valuelable;
            
        }else
        {
            _numField = textField;
            _numLabValue = valuelable;
        }
        
    }
}
#pragma  mark -----懒加载 右边控件
- (UILabel *)pricetitle
{
    if (!_pricetitle) {
        _pricetitle = [[UILabel alloc] initWithFrame:CGRectMake(RealValue_W(416),_purchaseButton.mj_y,RealValue_W(120), 14)];
        _pricetitle.textColor =  MAINTITLECOLOR1;
        _pricetitle.font = AutoFont(12);
        _pricetitle.text = Localized(@"hone_price");
        
    }
    return _pricetitle;
}

- (UILabel *)numbertitle
{
    if (!_numbertitle) {
        _numbertitle = [[UILabel alloc] initWithFrame:CGRectMake(UIScreenWidth - 15 -RealValue_W(120),_pricetitle.mj_y,RealValue_W(120), 14)];
        _numbertitle.textColor =  MAINTITLECOLOR1;
        _numbertitle.font = AutoFont(12);
        _numbertitle.text = Localized(@"hone_num");
        _numbertitle.textAlignment = NSTextAlignmentRight;
    }
    return _numbertitle;
}
- (UITableView *)ToptableView
{
    if (!_ToptableView) {
        _ToptableView = [[UITableView alloc]initWithFrame:CGRectMake(_pricetitle.mj_x,_pricetitle.bottom + RealValue_W(20), (UIScreenWidth - RealValue_W(416) -15), RealValue_W(210))style:UITableViewStylePlain];
        _ToptableView.tableFooterView = [UIView new];
        _ToptableView.separatorColor = CLEARCOLOR;
        _ToptableView.delegate = self;
        _ToptableView.dataSource=self;
        _ToptableView.backgroundColor = TABLEVIEWLCOLOR;
        _ToptableView.showsVerticalScrollIndicator = NO;
        [_ToptableView registerClass:[NewTransactionCell class] forCellReuseIdentifier:@"NewTransactionCell"];
    }
    return _ToptableView;
}
- (UILabel *)priceLable
{
    if (!_priceLable) {
        _priceLable = [[UILabel alloc] initWithFrame:CGRectMake(_pricetitle.mj_x, _ToptableView.bottom, _ToptableView.width/2, 48)];
        _priceLable.textColor =  ZHANGCOLOR;
        _priceLable.font = AutoBoldFont(12);
        
    }
    return _priceLable;
}
- (UILabel *)rangeLable
{
    if (!_rangeLable) {
        _rangeLable = [[UILabel alloc] initWithFrame:CGRectMake(_priceLable.right, _ToptableView.bottom, _ToptableView.width/2, 48)];
        _rangeLable.textColor =  ZHANGCOLOR;
        _rangeLable.font = AutoBoldFont(12);
        _rangeLable.textAlignment = NSTextAlignmentRight;
        
    }
    return _rangeLable;
}
- (UITableView *)bottombleView
{
    if (!_bottombleView) {
        _bottombleView = [[UITableView alloc]initWithFrame:CGRectMake(_priceLable.mj_x,_priceLable.bottom , _ToptableView.width, RealValue_W(210))style:UITableViewStylePlain];
        _bottombleView.tableFooterView = [UIView new];
        _bottombleView.separatorColor = CLEARCOLOR;
        _bottombleView.delegate = self;
        _bottombleView.dataSource=self;
        _bottombleView.backgroundColor = TABLEVIEWLCOLOR;
        _bottombleView.showsVerticalScrollIndicator = NO;
        [_bottombleView registerClass:[NewTransactionCell class] forCellReuseIdentifier:@"NewTransactionCell"];
    }
    return _bottombleView;
}


#pragma  mark -----懒加载 左边控件
- (UIButton *)chooseType
{
    if (!_chooseType) {
        _chooseType = [[UIButton alloc] initWithFrame:CGRectMake(15, _purchaseButton.bottom + 17, 100, 16)];
        [_chooseType setTitle:Localized(@"transaction_Limited_transaction") forState:(UIControlStateNormal)];
        [_chooseType setTitleColor:MAINTITLECOLOR forState:UIControlStateNormal];
        [_chooseType setImage:[UIImage imageNamed:@"Drop-down"] forState:UIControlStateNormal];
        _chooseType.titleLabel.font = AutoBoldFont(13);
        [_chooseType setTitleEdgeInsets:UIEdgeInsetsMake(0, -_chooseType.imageView.width , 0, _chooseType.imageView.width)];
        [_chooseType setImageEdgeInsets:UIEdgeInsetsMake(0, _chooseType.titleLabel.width + 10, 0, - _chooseType.titleLabel.width)];
        [_chooseType addTarget:self action:@selector(transactionButton:) forControlEvents:UIControlEventTouchUpInside];
        _chooseType.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;// 水平左对齐
    }
    return _chooseType;
}

- (UILabel *)sellnumLabValue
{
    if (!_sellnumLabValue) {
        _sellnumLabValue = [[UILabel alloc] initWithFrame:CGRectMake(_numLabValue.mj_x, _numLabValue.bottom +RealValue_W(13), RealValue_W(344), RealValue_W(26))];
        _sellnumLabValue.textColor = MAINTITLECOLOR1;
        _sellnumLabValue.font = AutoFont(12);
    }
    return _sellnumLabValue;
}
- (UILabel *)ATurnover
{
    if (!_ATurnover) {
        _ATurnover = [[UILabel alloc] initWithFrame:CGRectMake(15,_buyButton.mj_y - RealValue_W(60 +26), RealValue_W(344), RealValue_W(26))];
        _ATurnover.textColor =  MAINTITLECOLOR1;
        _ATurnover.font = AutoFont(12);
        _ATurnover.adjustsFontSizeToFitWidth = YES;
    }
    return _ATurnover;
}
- (UIButton *)buyButton
{
    if (!_buyButton) {
        _buyButton = [UIButton dd_buttonCustomButtonWithFrame:CGRectMake(RealValue_W(30), self.height -RealValue_W(46) - RealValue_W(70), RealValue_W(344), RealValue_W(70)) title:Localized(@"hone_Purchase") backgroundColor:ZHANGCOLOR titleColor:WHITECOLOR tapAction:^(UIButton *button) {
            [self buy:button];
        }];
        
        _buyButton.layer.masksToBounds     =YES;
        _buyButton.layer.cornerRadius      =2;
        _buyButton.titleLabel.font = AutoFont(15);
        [_buyButton setTitle:Localized(@"C2C_buy") forState:UIControlStateNormal];
        [_buyButton setTitle:Localized(@"hone_sell") forState:UIControlStateSelected];
        UIImage * backImageNormal = [[UIImage alloc] createImageWithSize:CGSizeMake(_buyButton.width, _buyButton.height) gradientColors:@[(id)ColorStr(@"#45D69E"),(id)ColorStr(@"#45D69E"),(id)ColorStr(@"#3EC28F")] percentage:@[@(0.0),@(0.59),@(1)] gradientType:GradientFromLeftToRight];
        
        UIImage * backImageSelected = [[UIImage alloc] createImageWithSize:CGSizeMake(_buyButton.width,  _buyButton.height) gradientColors:@[(id)ColorStr(@"#fa6478"),(id)ColorStr(@"#fa6478"),(id)ColorStr(@"#fa4a61")] percentage:@[@(0.0),@(0.59),@(1)] gradientType:GradientFromLeftToRight];
        
        [_buyButton setBackgroundImage:backImageNormal forState:UIControlStateNormal];
        [_buyButton setBackgroundImage:backImageSelected forState:UIControlStateSelected];
    }
    return _buyButton;
}

- (void)getslider:(NSInteger )index
{
    //    _slider.hidden = YES;
    for (UIView *view in self.subviews) {
        if (view.tag == 10086) {
            [view removeFromSuperview];
        }
    }
    CCHStepSizeSlider *slider = [[CCHStepSizeSlider alloc] initWithFrame:CGRectMake(-RealValue_W(10), _numField.bottom+8, RealValue_W(436), 40)];
    slider.titleArray = @[@"0%",@"25%",@"50%",@"75%",@"100%"];
    slider.lineWidth = 3;
    slider.titleOffset = 15;
    slider.index = index;
    slider.stepWidth = 12;
    slider.sliderOffset = -8;
    slider.stepTouchRate = 2;
    slider.thumbSize = CGSizeMake(12, 12);
    slider.thumbTouchRate = 4;
    
    NSString *language=[ZBLocalized sharedInstance].AppbBGColor;
    
    if ([NSString isEmptyString:language] ||[language isEqualToString:BLACK_COLOR]) //app风格为默认色
    {
        slider.thumbImage=  [UIImage imageNamed:@"sliderImage"];
        
    }else if ([language isEqualToString:WHITE_COLOR])//app风格为白色
    {
        slider.thumbImage=  [UIImage imageNamed:@"sliderImage1"];
    }
    
    slider.continuous = NO;
    slider.ChoosestepColor = ZHANGCOLOR;
    slider.stepColor = [ZBLocalized sharedInstance].sliderbgColor;
    slider.lineColor = slider.stepColor;
    
    slider.tag = 10086;
    [slider addTarget:self action:@selector(valueChangeAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:slider];
}

/*获取币价深度和降度
 *asks 深度
 *bids
 *rangeIndex 数组的后几位
 */
- (void)getDepthDataWithasks:(NSArray *)asks
                        bids:(NSArray *)bids
                  rangeIndex:(NSInteger)rangeIndex

{
    if (asks.count>=rangeIndex) {
        
        _asks = [asks subarrayWithRange:NSMakeRange(asks.count -rangeIndex, rangeIndex)];
    }else
    {
        _asks = asks;
    }
    if (bids.count>=rangeIndex) {
        _bids = [bids subarrayWithRange:NSMakeRange(0, rangeIndex)];
    }else
    {
        _bids = bids;
    }
    [self.ToptableView reloadData];
    [self.bottombleView reloadData];
    
}
- (void)uploadPrice:(NSString *)price
{
    _priceField.text = price;
    [self RefreshThePrice];
}
#pragma  mark -----tableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return RealValue_W(44);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView ==self.ToptableView) {
        
        return _asks.count;
    }else
    {
        return _bids.count;
    }
    
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewTransactionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewTransactionCell"];
    if (tableView ==_ToptableView) {
        
        
        cell.leftlable.text = [EXUnit asksOrbadsformatternumber:_modle.quote_asset_precision.intValue assess:_asks[indexPath.row][0]];
        cell.rightlable.text = [EXUnit asksOrbadsformatternumber:_modle.base_asset_precision.intValue assess:_asks[indexPath.row][1]];
        cell.leftlable.textColor = DIEECOLOR;
    }else
    {
        cell.leftlable.text =  [EXUnit asksOrbadsformatternumber:_modle.quote_asset_precision.intValue assess:_bids[indexPath.row][0]];
        cell.rightlable.text = [EXUnit asksOrbadsformatternumber:_modle.base_asset_precision.intValue assess:_bids[indexPath.row][1]];
        cell.leftlable.textColor = ZHANGCOLOR;
    }
    WeakSelf
    cell.getPriceblock = ^(NSString *price) {
        
        [weakSelf uploadPrice:price];
    };
    
    return cell;
    
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField ==_priceField) {
        if (_canEditing) {
            return YES;
        }else return NO;
    }
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    //删除处理
    if ([string isEqualToString:@""]) {
        return YES;
    }
    //首位不能为.号
    if (range.location == 0 && [string isEqualToString:@"."]) {
        return NO;
    }
    return [self isRightInPutOfString:textField.text withInputString:string range:range textField:textField];
}


- (BOOL)isRightInPutOfString:(NSString *) string withInputString:(NSString *) inputString range:(NSRange) range textField:(UITextField *)textField{
    //判断只输出数字和.号
    NSString *passWordRegex = @"[0-9\\.]";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    if (![passWordPredicate evaluateWithObject:inputString]) {
        return NO;
    }
    
    //逻辑处理
    if ([string containsString:@"."]) {
        if ([inputString isEqualToString:@"."]) {
            return NO;
        }
        NSRange subRange = [string rangeOfString:@"."];
        if (textField == _priceField) {
            if (range.location - subRange.location > _modle.quote_asset_precision.intValue) {
                return NO;
            }
        }else if (textField ==_numField)
        {
            if (range.location - subRange.location > _modle.base_asset_precision.intValue) {
                return NO;
            }
        }
        
    }
    return YES;
}
@end
